import styled from '@emotion/styled';
import React, { useRef } from 'react';
import { formatContent } from '../utils';

export default function Typora() {
    const markdownRef = useRef<HTMLDivElement | null>(null);
    const setRange = ()=>{
        let range = document.createRange();
        range.selectNodeContents(markdownRef!.current);
        range.collapse(false);
        let sel = window.getSelection();
        sel!.removeAllRanges();
        sel!.addRange(range);
    };
    const markdownChangeHandler = (e:React.SyntheticEvent<HTMLDivElement>)=>{
        e.currentTarget.innerHTML = formatContent(e.currentTarget.innerHTML);
        setRange();
    };
    return (
        <Container contentEditable={true} ref={markdownRef} onInput={markdownChangeHandler}/>
    );
}

const Container = styled.div`
    width: 100%;
    height: 100%;
    outline: none;
    caret-color: purple;
`;